//
//  ShoppingCartDetailView.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/6.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//
//  商品详情头视图
protocol ShoppingDetailViewDelegate: NSObjectProtocol {
    func allCommentTap()
}
import UIKit
import Kingfisher
import WebKit

class ShoppingDetailView: UIView, WKNavigationDelegate, WKUIDelegate, FSPagerViewDelegate, FSPagerViewDataSource, BottomShadow, AddCornerUIRectCorner {
    
    private let bannerHeight: CGFloat = 211
    private let pageControlHeight: CGFloat = 25
    let tempContent = "重"
    var bannerView = FSPagerView()
    var pageControl = FSPageControl()
    var commodiytModel = GoodsModel()
    private var recommendData: [GoodsModel] = []
    weak var delegate: ShoppingDetailViewDelegate?
    static var cellLineMargin: CGFloat = 10
    static let topHeight: CGFloat  = 26
    static let centerViewHeight: CGFloat  = 329
    static let bottomViewHeight: CGFloat = 21
    var commodityColletion:UICollectionView?
    var consultationCollectionView:ConsultationCollectionView = ConsultationCollectionView()
    var commentCountLabel = UILabel()
    var praiseRateLabel = UILabel()
    var webView: WKWebView?
    
    var delegateVc: UIViewController?
    typealias selectBlock = () -> Void
    var selectblock: selectBlock?
    var refreshBlock: selectBlock?
    // MARK: - 初始化方法
    init() {
        super.init(frame: .zero)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置界面
    func setUIAndData(commodiytModel :GoodsModel) {
        self.commodiytModel = commodiytModel
        self.backgroundColor = ONColor.cellBGColor
        let showView = setBannerData {[unowned self] (bannerView, pageControl, contentHeight) in
            bannerView.delegate = self
            bannerView.dataSource = self
            self.bannerView = bannerView
            self.pageControl = pageControl
            if(commodiytModel.fileInfos != nil){
                self.pageControl.numberOfPages = (commodiytModel.fileInfos?.count)!
            }
        }
        self.addSubview(showView)
        
        let itemView = itemContentView(sView: self, topView: showView, subView: {(nameLabel, subContentLabel, priceLabel, originalPriceLabel, selectButton) in
            nameLabel.text = commodiytModel.goodsName!
            //            if let img = commodiytModel.coverPath {
            //                let path:String = "\(BaseURL)\(img)"
            //                
            //                let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
            //                rightImageView.sd_setAnimationImages(with: [url! as URL])
            //            }
            
            subContentLabel.text = commodiytModel.goodsAlias!
            let specifications = commodiytModel.specifications![0]
            priceLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥：", firstColor: ONColor.normalTextColor, firstSize: 14), second: (secondString: NSString(string: specifications.price!), secondColor: ONColor.searchButtomColor, secondSize: 14))
            originalPriceLabel.attributedText = NSMutableAttributedString.strikethrough(str: "￥：" + specifications.originalPrice!)
            
        })
        
        itemView.layoutIfNeeded()
        itemView.setNeedsLayout()
        
        let originY = kHeight(r: bannerHeight) + 130 + 10 + 10 + 10
        let webView = setWebView(originY: originY)
        self.addSubview(webView)
        webView.load(URLRequest(url: appendUrl(suffix:commodiytModel.contentUrl!)))
//        webView.load(URLRequest(url: appendUrl(suffix: commodiytModel.shareUrl!)))
        consultationCollectionView.frame = CGRect(x: 0, y: kHeight(r: bannerHeight) + 130 + 10 + 10 + 30, width: ScreenWidth, height: 125)
        consultationCollectionView.delegateVc = self.delegateVc
        self.addSubview(consultationCollectionView)
        
        let commentView = userComment(sView: self, topView: consultationCollectionView, subViewClosure: { (commentCountLabel, praiseRateLabel) in
//            commentCountLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "用户评价  ", firstColor: ONColor.normalTextColor, firstSize: 15), second: (secondString: "\(0)" as NSString, secondColor: ONColor.normalTextColor, secondSize: 12))
//            let max: CGFloat = CGFloat(5) * 5.0
//            var subData: CGFloat = 0
//            for item in commodiytModel.commodityCommentModel {
//                subData += CGFloat(item.grade)
//            }
//
//            let praiseRate = (subData / max) * 100
//            praiseRateLabel.text =  String(format: "%.1f", 80) + "好评"
        })
        
        
        commentView.layoutIfNeeded()
//        let collectionHeight =  getColletctionHeight().commodityColletionHeight
//        self.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: showView.height + itemView.height + commentView.height + 10 + 10 + 10)
//        

    }
    
    func setWebView(originY: CGFloat) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.x = 10;
        webView.y = originY
        webView.width = ScreenWidth - 20
        webView.height = 10
        return webView;
    }
    
    func updateCollectionViewData(recommend:[GoodsModel]) -> Void {
        recommendData = recommend
        print(recommendData)
        consultationCollectionView.setData(arr: recommend)

    }
    func updateCommentHeader(count:String,rate:String) -> Void {
        commentCountLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "用户评价  ", firstColor: ONColor.normalTextColor, firstSize: 15), second: (secondString: "\(count)" as NSString, secondColor: ONColor.normalTextColor, secondSize: 12))
        praiseRateLabel.text =  rate + "好评"

    }
    func setBannerData(viewsClosure: (FSPagerView, FSPageControl, CGFloat) -> Void ) -> UIView {
        let bannerView = FSPagerView()
        let pageControl = FSPageControl()
        bannerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: kHeight(r: bannerHeight))
        bannerView.isInfinite = true
        bannerView.automaticSlidingInterval = 2
        
        self.setShadow(view: bannerView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: 0)
        
        bannerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        pageControl.frame = CGRect(x: 0, y: bannerView.height - pageControlHeight, width: bannerView.width, height: pageControlHeight)
        pageControl.contentHorizontalAlignment = .center
        pageControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        pageControl.itemSpacing = 8
        
        let mainView = UIView()
        mainView.backgroundColor = UIColor.red
        var rect = bannerView.frame
        rect.size.height += 10
        mainView.frame = rect
        mainView.backgroundColor = ONColor.cellBGColor
        mainView.addSubview(bannerView)
        mainView.addSubview(pageControl)
        viewsClosure(bannerView, pageControl, bannerView.height)
        return mainView
    }

    func itemContentView(sView: UIView, topView: UIView, subView: (_ nameLabel :UILabel,  _ subContentLabel: UILabel, _ priceLabel: UILabel, _ originalPriceLabel: UILabel, _ specificationsButton: UIButton) -> Void) -> UIView {
        
        // 常量
        let firstTopMargin: CGFloat  = 15
        let otherTopMargin: CGFloat  = 5
        let sideMargin: CGFloat = 14
        let imageSize: CGFloat = 130
        /**
         设置
         **/
        topView.layoutIfNeeded()
        let mainView = UIView()
        mainView.backgroundColor = UIColor.white
        sView.addSubview(mainView)
        mainView.snp.makeConstraints { (make) in
            make.left.equalTo(sView.snp.left).offset(10)
            make.right.equalTo(sView.snp.right).offset(-10)
            make.top.equalTo(topView.snp.bottom).offset(0)
            make.height.equalTo(imageSize)
        }
        
        let nameLabel = UILabel()
        nameLabel.font = UIFont.systemFont(ofSize: 14)
        nameLabel.textColor = ONColor.normalTextColor
        mainView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(mainView.snp.left).offset(sideMargin)
            make.top.equalTo(mainView.snp.top).offset(otherTopMargin)
            make.right.equalTo(mainView.snp.right).offset(10)
        }
        
        let subContentLabel = UILabel()
        subContentLabel.font = UIFont.systemFont(ofSize: 10)
        subContentLabel.textColor = ONColor.subTextColor
        mainView.addSubview(subContentLabel)
        subContentLabel.snp.makeConstraints { (make) in
            make.left.equalTo(mainView.snp.left).offset(sideMargin)
            make.top.equalTo(nameLabel.snp.bottom).offset(otherTopMargin)
            make.right.equalTo(mainView.snp.right).offset(sideMargin)
        }
        
        let priceLabel = UILabel()
        mainView.addSubview(priceLabel)
        priceLabel.snp.makeConstraints { (make) in
            make.left.equalTo(mainView.snp.left).offset(sideMargin)
            make.top.equalTo(subContentLabel.snp.bottom).offset(otherTopMargin)
        }
        
        let originalPriceLabel = UILabel()
        originalPriceLabel.font = UIFont.systemFont(ofSize: 14)
        originalPriceLabel.textColor = ONColor.subTextColor
        mainView.addSubview(originalPriceLabel)
        originalPriceLabel.snp.makeConstraints { (make) in
            make.left.equalTo(priceLabel.snp.right).offset(16)
            make.centerY.equalTo(priceLabel.snp.centerY)
        }
        
        let alreadyChosenLabel = UILabel()
        alreadyChosenLabel.text = "已选择："
        alreadyChosenLabel.font = UIFont.systemFont(ofSize: 14)
        alreadyChosenLabel.textColor = ONColor.normalTextColor
        mainView.addSubview(alreadyChosenLabel)
        alreadyChosenLabel.snp.makeConstraints { (make) in
            make.left.equalTo(mainView.snp.left).offset(sideMargin)
            make.top.equalTo(priceLabel.snp.bottom).offset(16)
            make.width.greaterThanOrEqualTo(50)
        }
        let specarry:Array = commodiytModel.specifications!
        if specarry.count > 0 {
            let specifications = commodiytModel.specifications![0]
            
            let selectButton = UIButton(type: .custom)
            selectButton.setTitle(specifications.color!, for: .normal)
            selectButton.setTitleColor(ONColor.searchButtomColor, for: .normal)
            selectButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            selectButton.addTarget(self, action: #selector(selectTap(_ :)), for: .touchUpInside)
            mainView.addSubview(selectButton)
            selectButton.snp.makeConstraints { (make) in
                make.top.equalTo(priceLabel.snp.bottom).offset(16)
                make.left.equalTo(alreadyChosenLabel.snp.right).offset(2)
                make.centerY.equalTo(alreadyChosenLabel.snp.centerY)
                make.width.greaterThanOrEqualTo(80)
            }
            
            let iconImageView = UIImageView(image: UIImage(named: "btn_arrow_black"))
            mainView.addSubview(iconImageView)
            iconImageView.snp.makeConstraints { (make) in
                make.left.equalTo(selectButton.snp.right).offset(5)
                make.centerY.equalTo(selectButton.snp.centerY)
                //            make.centerX.equalTo(selectButton.snp.centerX)
            }
            subView(nameLabel, subContentLabel, priceLabel, originalPriceLabel, selectButton)
            
            self.setShadow(view: mainView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        }
        
        return mainView
    }
    
    /// 设置推荐CollectionView
    ///
    /// - Returns: 返回
    func setConsultationCollectionView(sView: UIView, topView: UIView, subViewClosure: (ConsultationCollectionView) -> Void) -> ConsultationCollectionView {
        let consultationHeight: CGFloat = 125
        
        let consultationCV = ConsultationCollectionView()
        sView.addSubview(consultationCV)
        consultationCV.snp.makeConstraints { (make) in
            make.left.right.equalTo(sView)
            make.top.equalTo(topView.snp.bottom)
            make.height.equalTo(consultationHeight)
        }
        subViewClosure(consultationCV)
        return consultationCV
    }
   
    
    /// 设置评论头
    ///
    /// - Parameters:
    ///   - sView: 爸爸
    ///   - topView: 顶部视图
    
    func userComment(sView: UIView, topView: UIView, subViewClosure: (_ countLabel: UILabel, _ praiseRateLabel: UILabel) -> Void) -> UIView {
        
        let height: CGFloat = 26
        let mainViewSideMargin: CGFloat = 10
        let leftMargin: CGFloat = 14
        
        let mainView = UIView()
        mainView.backgroundColor = UIColor(hex: 0xC7C7C7)
        mainView.isUserInteractionEnabled = true
        sView.addSubview(mainView)
        
        self.addCornerWithView(aView: mainView, aCorners: [.topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        mainView.snp.makeConstraints { (make) in
            make.left.equalTo(sView.snp.left).offset(mainViewSideMargin)
            make.right.equalTo(sView.snp.right).offset(-mainViewSideMargin)
            make.top.equalTo(topView.snp.bottom)
            make.height.equalTo(height)
        }
        
        commentCountLabel.textColor = UIColor.black
        commentCountLabel.font = UIFont.systemFont(ofSize: 14)
        mainView.addSubview(commentCountLabel)
        commentCountLabel.snp.makeConstraints { (make) in
            make.left.equalTo(mainView.snp.left).offset(leftMargin)
            make.centerY.equalTo(mainView.snp.centerY)
        }
        
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(commentMore(_:)), for: .touchUpInside)
        button.backgroundColor = UIColor.clear
        mainView.addSubview(button)
        button.snp.makeConstraints { (make) in
            make.right.equalTo(mainView.snp.right).offset(-leftMargin)
            make.centerY.equalTo(mainView.snp.centerY)
            make.size.equalTo(CGSize(width: 150, height: height))
        }
        
        let rightImageView = UIImageView(image: UIImage(named: "btn_arrow_black"))
        mainView.addSubview(rightImageView)
        rightImageView.snp.makeConstraints { (make) in
            make.right.equalTo(mainView.snp.right).offset(-leftMargin)
            make.centerY.equalTo(mainView.snp.centerY)
        }
        
        praiseRateLabel.textColor = ONColor.normalTextColor
        praiseRateLabel.font = UIFont.systemFont(ofSize: 14)
        mainView.addSubview(praiseRateLabel)
        praiseRateLabel.snp.makeConstraints { (make) in
            make.right.equalTo(rightImageView.snp.left).offset(-5)
            make.centerY.equalTo(rightImageView.snp.centerY)
        }
        subViewClosure(commentCountLabel, praiseRateLabel)
        return mainView
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        var frame = webView.frame
        webView.scrollView.isScrollEnabled = true
        webView.scrollView.bounces = true
        webView.isUserInteractionEnabled = true
        webView.evaluateJavaScript("document.body.scrollHeight") { (result, error) in
            let height: CGFloat = result as! CGFloat
            webView.height = height
            webView.scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width * 2, height: height)
            let btt: CGFloat = webView.bottom
            self.consultationCollectionView.frame = CGRect(x: 0, y: btt + 10, width: ScreenWidth, height: 125)
            self.height = 125 + 26 + 10 + btt
            self.refreshBlock?()
            self.layoutIfNeeded()
        }
        
    }

    @objc func commentMore(_ btn: UIButton) {
        self.delegate?.allCommentTap()
    }
    
    @objc func selectTap(_ btn: UIButton) {
        self.selectblock!()
    }
    
    // MARK: - FSPagerView DataSource
    
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        if let count = commodiytModel.fileInfos?.count {
            return count
        }
        return 0
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        cell.isDescribeLabel = false
        let fileinfo = commodiytModel.fileInfos![index]
        if let img = fileinfo.filePath {
            let path:String = "\(BaseURL)\(img)"
            
            
            let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
            cell.imageView?.sd_setImage(with: appendUrl(suffix: img), completed: nil)
        }
        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.clipsToBounds = true
        cell.textLabel?.text = fileinfo.fileName!
        cell.textLabel?.font = UIFont.systemFont(ofSize: 15)
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        self.pageControl.currentPage = index
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        guard self.pageControl.currentPage != pagerView.currentIndex else {
            return
        }
        self.pageControl.currentPage = pagerView.currentIndex
    }
}
